<template>
  <!-- 上岗培训页面 -->
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot="menuLeft">
        <el-button v-if="permission.InductionTraining_add" type="primary" size="small" icon="el-icon-plus" @click="addBreakRow">新 增 </el-button>
        <el-button v-if="permission.InductionTraining_del" type="danger" size="small" icon="el-icon-delete" plain @click="handleDelete">删 除 </el-button>
        <el-button v-if="permission.InductionTraining_start" type="info" size="small" icon="el-icon-caret-right" @click="changeStatus(1)">开 始 </el-button>
        <el-button v-if="permission.InductionTraining_success" type="success" size="small" icon="el-icon-success" @click="changeStatus(2)">完 成 </el-button>
      </template>
      <template slot-scope="{ row, index }" slot="menu">
        <!-- <el-button
          type="text"
          icon="el-icon-edit"
          v-if="isEditBtn"
          size="small"
          :disabled="row.status == 3"
          plain
          style="border: 0; background-color: transparent !important"
          @click.stop="openEditForm(row)"
          >编辑
        </el-button> -->
        <el-button :disabled="row.status == 3" type="text" size="small" @click="openEditForm(row, index)">{{ row.$cellEdit ? '保存' : '修改' }}</el-button>
        <el-button v-if="row.$cellEdit" type="text" size="small" @click="$refs.crud.rowCancel(row, index)">取消</el-button>
        <el-button
          v-if="permission.InductionTraining_upload"
          @click="openDialog(row)"
          type="text"
          size="small"
          plain
          style="border: 0; background-color: transparent !important"
        >
          上传
        </el-button>

        <el-button
          v-if="permission.InductionTraining_download"
          type="text"
          size="small"
          plain
          @click="downloadFile(row)"
          style="border: 0; background-color: transparent !important"
          >下载</el-button
        >
      </template>

      <template slot-scope="{ row }" slot="status">
        <el-tag v-if="row.status == 1">未开始</el-tag>
        <el-tag type="danger" v-if="row.status == 2">培训中</el-tag>
        <el-tag type="success" v-if="row.status == 3">已完成</el-tag>
      </template>
    </avue-crud>
    <el-dialog append-to-body :title="上传" :visible.sync="printLabelModal" @close="closeDialog">
      <avue-form class="upload-form-avue" ref="printLabelForm" v-model="printLabelForm" v-if="printLabelModal" :option="printLabelOption" :upload-after="uploadAfter">
      </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="onSaveFile">确 定</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="printLabelModal = false">取 消</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, add, getSubjectList, remove } from '@/api/product/Induction-training';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';

export default {
  name: 'ProductInductionTraining',
  components: {
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'INDUCTION_TRAINING',
      form: {
        shiftGroupId: ''
      },
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      data: [],
      selectData: [],
      code: '00',
      searchLabelWidth: 100,
      isEditBtn: true,
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,

        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        dialogClickModal: false,
        searchLabelWidth: 120,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        addRowBtn: false,
        // cellBtn: true,
        cellBtn: false,
        cancelBtn: false,
        // menuWidth: 250,
        selection: true,
        // select: true,
        columnBtn: false,
        column: [
          {
            label: '培训课题',
            prop: 'subjectId',
            labelWidth: 120,
            width: 120,

            type: 'select',
            // dataType: "number",
            order: 1,
            cell: true,
            filterable: true,
            // dicUrl: '/api/mes-product/trainingsubject/key-value',
            dicData: [],
            props: {
              label: 'subject',
              value: 'subjectId'
            },
            rules: [
              {
                required: true,
                message: '请输入内容',
                trigger: 'blur'
              }
            ],
            change: (val, column) => {
              val.column.dicData.forEach((item) => {
                if (item.subjectId == val.value) {
                  val.row.subjectType = this._get(item, 'subjectType', '');
                  val.row.subject = this._get(item, 'subject', '');
                }
              });
            }
          },
          {
            label: '培训类型',
            prop: 'subjectType',
            labelWidth: 120,
            type: 'select',
            order: 2,
            dicUrl: '/api/blade-system/dict/dictionary?code=TRAINING_SUBJECT_TYPE',
            search: true,
            searchOrder: 1,
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请输入内容',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '培训讲师',
            prop: 'coach',
            labelWidth: 120
          },
          {
            label: '培训班组',
            prop: 'shiftGroupId',
            type: 'select',
            labelWidth: 120,
            // 是否开启多选
            // multiple: true,
            filterable: true,
            minWidth: 150,
            search: true,
            searchOrder: 1,
            order: 3,
            cell: true,
            dicUrl: '/api/mes-admin/shift-group/key-value',
            props: {
              label: 'shiftGroupName',
              value: 'shiftGroupId'
            },
            rules: [
              {
                required: true,
                message: '请选择培训班组',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '培训开始时间',
            prop: 'startDate',
            width: 135,
            type: 'datetime'
          },
          {
            label: '培训结束时间',
            prop: 'endDate',
            width: 135,
            type: 'datetime1'
          },
          {
            label: '状态',
            prop: 'status'
          },
          {
            label: '附件',
            prop: 'fileAttachName',
            width: 120
          }
        ]
      },
      tableOption: {}, //公用模态框配置信息
      printLabelModal: false,
      printLabelForm: {},
      printLabelOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 110,
        column: [
          {
            label: '上传附件',
            labelWidth: 140,
            prop: 'fileUrl',
            type: 'upload',
            loadText: '附件上传中，请稍等',
            propsHttp: {
              url: 'link',
              name: 'originalName',
              res: 'data'
            },
            listType: 'text',
            limit: 1,
            accept: '.ppt',
            tip: '只能上传ppt文件',
            action: '/api/blade-resource/oss/endpoint/put-file-attach',
            rules: [
              {
                required: true,
                message: '请上传附件',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      // 选中的一项
      selectRow: {}
    };
  },
  watch: {},
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.location_add, false),
        viewBtn: this.vaildData(this.permission.location_view, false),
        delBtn: this.vaildData(this.permission.location_delete, false),
        editBtn: this.vaildData(this.permission.location_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
    this.getSubjectList();
  },
  methods: {
    /**
     * 上传后方法
     */
    uploadAfter(res, done, loading, column) {
      this.printLabelForm.labelAttachId = res.attachId;
      this.printLabelForm.fileName = res.originalName;
      this.printLabelForm.link = res.link;
      done();
    },

    openEditForm(row) {
      this.$refs.crud.rowCell(row, row.$index);
    },
    openDialog(row) {
      this.selectRow = row;
      this.printLabelModal = true;
    },
    downloadFile(row) {
      if (!row.fileUrl) {
        this.$message.error('请先上传后再下载附件！');
        return;
      }
      const a_link = document.createElement('a'); // 生成一个a链接
      // // 将链接地址字符内容转变成blob地址
      a_link.href = row.fileUrl;
      if (row.fileAttachName) {
        a_link.download = row.fileAttachName; //下载的文件的名字
      }
      document.body.appendChild(a_link);
      a_link.click();

      // const x = new window.XMLHttpRequest();
      // x.open('GET', row.fileUrl, true);
      // x.responseType = 'blob';
      // x.onload = () => {
      //     // const url = window.URL.createObjectURL(x.response);
      //     const url = window.URL.createObjectURL(x.response)
      //     a_link.href = url;
      //     if (row.fileAttachName) {
      //         a_link.download = row.fileAttachName; //下载的文件的名字

      //     } else {
      //         a_link.download = '123456.ppt'
      //     }
      //     console.log(a_link)

      //     a_link.click();
      // };
      // x.send();
    },

    closeDialog() {
      this.$refs.printLabelForm.resetFields();
      this.printLabelForm = {};
    },
    // 获取培训课题列表
    getSubjectList() {
      getSubjectList().then((res) => {
        const column = this.findObject(this.option.column, 'subjectId');
        column.dicData = res.data.data;
      });
    },
    // 新增一行
    addBreakRow() {
      const userInfo = JSON.parse(localStorage.getItem('saber-userInfo'));

      this.data.splice(0, 0, {
        $cellEdit: true,
        coach: userInfo.content.user_name,
        coachId: userInfo.content.user_id
      });
    },
    // 上传文件
    async onSaveFile() {
      var item = this.selectRow;
      if (!this.printLabelForm.link) {
        this.$message.error('请先上传一个文件再操作！');
        return;
      }
      item.fileUrl = this.printLabelForm.link;
      item.fileAttachId = this.printLabelForm.labelAttachId;
      item.fileAttachName = this.printLabelForm.fileName;
      await this.rowSave(item);
      this.printLabelModal = false;
    },
    changeStatus(type) {
      if (this.selectionList.length < 1) {
        this.$message.error('请先选择一项再操作！');
        return;
      }
      var item = this.selectionList[0];
      if (type === 1) {
        if (item.status != 1) {
          this.$message.error('请确保所选项为未开始状态！');
          return;
        }
        item.operation = 1;
        item.startDate = this.$moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
      } else {
        if (item.status != 2) {
          this.$message.error('请确保所选项为培训中状态！');
          return;
        }
        item.operation = 2;
        item.endDate = this.$moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
      }

      this.rowSave(item);
    },
    rowSave(row, done, loading) {
      const obj = {
        subjectId: this._get(row, 'subjectId', ''),
        id: this._get(row, 'id', null),
        subjectType: this._get(row, 'subjectType', ''),
        subject: this._get(row, 'subject', ''),
        startDate: this._get(row, 'startDate', ''),
        endDate: this._get(row, 'endDate', ''),
        operation: this._get(row, 'operation', null),
        fileUrl: this._get(row, 'fileUrl', null),
        fileAttachId: this._get(row, 'fileAttachId', ''),
        fileAttachName: this._get(row, 'fileAttachName', ''),
        shiftGroupIdList: [this._get(row, 'shiftGroupId', null)],
        coach: this._get(row, 'coach', ''),
        coachId: this._get(row, 'coachId', '')
      };
      add(obj).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          if (done) {
            done();
          }
        },
        (error) => {
          if (loading) {
            loading();
          }
          this.onLoad(this.page);
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      this.rowSave(row, done, loading);
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(selection, row) {
      if (selection.length > 1) {
        const preVal = selection.shift();
        this.$refs.crud.toggleRowSelection(preVal, false);
      }
      this.selectionList = selection;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    getSelectData(code) {
      getSelectList(code)
        .then((res) => {
          this.selectData = res.data.data;
        })
        .catch((err) => {
          this.message(err);
        });
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        // [] || dataListTable
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.upload-form-avue {
  ::v-deep.el-upload__input {
    display: none !important;
  }
}
</style>
